package com.example.base.tools.upgrade

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import com.example.base.ext.getViewModel
import com.example.base.vm.onError

/**  负责下载升级事件的 Fragment  **/
class DownloadFragment : Fragment() {

    companion object {
        private const val DATA = "downloadInfo"

        fun getInstance(downloadInfo: DownloadInfo): DownloadFragment {
            val fragment = DownloadFragment()
            val params = Bundle()
            params.putParcelable(DATA, downloadInfo)
            fragment.arguments = params
            return fragment
        }
    }

    private val viewModel: DownloadViewModel by lazy {
        getViewModel<DownloadViewModel>()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val downloadInfo: DownloadInfo = arguments?.getParcelable(DATA)!!

        if (downloadInfo.apkSavePath.isEmpty())
            downloadInfo.apkSavePath = UpgradeTool.defaultPath(requireActivity())

        viewModel.downloadNewVersionAPK(downloadInfo, downloadListener) onError {
            Log.e("error", it)
        }
    }

    private var downloadListener: DownloadListener? = null

    /**  绑定下载状态监听器  **/
    fun bindDownloadListener(downloadListener: DownloadListener) {
        this.downloadListener = downloadListener
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if ((requestCode == UpgradeTool.REQUEST_INSTALL) and (resultCode == Activity.RESULT_OK)) {
            // TODO 安装成功, 程序被系统杀掉, 就不用处理了
        } else {
            // TODO 安装失败回调
        }
    }

}